<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Notice as NoticeModel;

class Notice extends BaseController
{
    public function list()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $page = input('page', 1, 'intval');
        $perpage = 10;
        $result = NoticeModel::order('id desc')->page($page, $perpage)->select();
        $total = NoticeModel::count();
        $data = [
            'total' => $total,
            'current' => $page,
            'perpage' => $perpage,
            'data' =>  $result
        ];
        return show(200, '通知列表', $data);
    }

    public function add()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $type = input('type', '');
        $title = input('title', '');
        $content = input('content', '');
        $result = NoticeModel::create([
            'type'  =>  $type,
            'title' =>  $title,
            'content' =>  $content,
            'time' => time()
        ]);
        if ($result) {
            return show(200, '添加成功');
        } else {
            return show(config('status.error_add'), '添加失败');
        }
    }

    public function edit()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $id = input('id', 0, 'intval');
        $data = NoticeModel::where('id', $id)->find()->toArray();
        return show(200, '查询成功', $data);
    }

    public function modify()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $id = input('id', 0, 'intval');
        $type = input('type', '');
        $title = input('title', '');
        $content = input('content', '');
        $result = NoticeModel::update([
            'id' => $id,
            'type'  =>  $type,
            'title' =>  $title,
            'content' =>  $content,
            'time' => time()
        ]);
        if ($result) {
            return show(200, '修改成功');
        } else {
            return show(config('status.error_update'), '修改失败');
        }
    }

    public function delete()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');
        $id = input('id', 0, 'intval');
        $result = NoticeModel::destroy($id);
        if ($result) {
            return show(200, '删除成功');
        } else {
            return show(config('status.error_delete'), '删除失败');
        }
    }
}
